import pygame

from lib.structure import Structure
from lib.dynamics import Mass, Constraint
from lib.geometry import lineIntersection

class Character(Structure):
    def __init__(self, root, pos):
        self.root = root
        self.world = root.world
        
        #Gameplay values
        self.heightStand = 24
        self.heightCrouch = 16
        self.height = self.heightStand
        self.speed = 0.2
        self.jump = 4
        
        #Structure
        self.feet = Mass(self.world, pos, weight=5)
        self.head = Mass(self.world, pos, weight=3)
        self.head.y -= self.height
        
        self.spine = Constraint(self.world, self.feet, self.head, stiffness=0.1)
        
        self.masses = [self.feet, self.head]
        self.constraints = [self.spine]
        
        self.structure = {}
        self.getStructure()
        
        self.fix = 0.5

    def update(self):
        self.handleStructure()
        self.handleInput()
    
    def handleInput(self):
        key = self.root.keyboard
        
        onGround = self.testGround(((self.feet.x, self.feet.y-0.5),
                                    (self.feet.x, self.feet.y+2.0)))
        
        #DIRECTIONAL MOVEMENT
        if key.check(pygame.K_LEFT):
            if onGround:
                self.feet.xPrev += self.speed
            else:
                self.feet.xPrev += self.speed / 2
        elif key.check(pygame.K_RIGHT):
            if onGround:
                self.feet.xPrev -= self.speed
            else:
                self.feet.xPrev -= self.speed / 2
        
        #JUMPING
        if key.check(pygame.K_UP):
            self.height = self.heightCrouch
        else:
            self.height = self.heightStand
        
        center = self.getCenter()
        self.structure[self.feet][1] = self.height / 2
        self.structure[self.head][1] = - self.height / 2
            
        if onGround:
            if key.checkReleased(pygame.K_UP):
                self.feet.y -= self.jump
    
    def testGround(self, line):
        #with Line = ((x, y), (x, y))
        p1, p2 = line
        for l in self.world.lines:
            if l.AABB.collidepoint(p1):
                lIntersection = lineIntersection(line, ((l.p1.x, l.p1.y), (l.p2.x, l.p2.y)))
                if lIntersection != None and lIntersection[2]:
                    return True
        return False
    
    def draw(self):
        surf = self.root.display
        
        for m in self.masses:
            pygame.draw.circle(surf, (0,0,0), (int(m.x), int(m.y)), 3*m.weight, 1)